/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package di.server.security;

import di.persistence.entities.User;
import di.persistence.entities.UserType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Kilian Ito
 */
@Service("assembler")
public class Assembler {
    protected final String prefix = "ROLE_";
    
    @Transactional(readOnly = true)
    public org.springframework.security.core.userdetails.User buildUserFromUserEntity(User user) {
        String username = user.getLogin();
        String password = user.getPassword();

        org.springframework.security.core.userdetails.User res;
        res = new org.springframework.security.core.userdetails.User(username, password, getAuthorities(user.getTypes()));
        return res;
    }
    
    protected Collection<GrantedAuthority> getAuthorities(Collection<UserType> types) {
        if (types == null && types.isEmpty())
            return null;
        
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (UserType role : types) {
            authorities.add(new SimpleGrantedAuthority(prefix+role.getLabel()));
            authorities.addAll(getAuthorities(role.getChildren()));
        }
        return authorities;
    }
}
